package com.pipe.connector.actor;

import com.pipe.exception.ProtocolCodecException;
import com.pipe.protocol.BasePackage;
import com.pipe.protocol.login.HandshakeResponsePacket;
import com.pipe.protocol.login.InitialHandshakePacket;
import com.pipe.util.PasswordSha;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Kiven
 */
public class DoLoginActor{
    private static Logger LOG = LoggerFactory.getLogger(DoLoginActor.class);
    private String userName;
    private String pwd;

    public DoLoginActor(String userName, String pwd) {
        this.userName = userName;
        this.pwd = pwd;
    }

    public HandshakeResponsePacket handler(String databaseName, BasePackage basePackage) throws ProtocolCodecException {
        try {
            LOG.info("[LOGGING] - InitialHandshakePacket received!");
            InitialHandshakePacket request = InitialHandshakePacket.build(basePackage.getPayLoadByteBuf());
            return new HandshakeResponsePacket(request.getCharacterSet(), this.userName,
                    PasswordSha.scramble411(this.pwd.getBytes("ISO-8859-1"), request.getSeed()), databaseName, "mysql_native_password");
        } catch (Exception e) {
            throw new ProtocolCodecException("[LOGGING] - Parse InitialHandshakePacket exception!", e);
        }
    }
}
